package com.adui.mgt.performance.service;


import com.adui.mgt.performance.common.CommonConstant;
import com.adui.mgt.performance.common.Result;
import com.adui.mgt.performance.entity.Role;
import com.adui.mgt.performance.mapper.RoleMapper;
import com.adui.mgt.performance.service.base.impl.BaseServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

import static com.adui.mgt.performance.common.CommonUtil.handleObjLog;

@Service
public class RoleService extends BaseServiceImpl<RoleMapper, Role> {

    public Role findRoleByCode(String roleCode) {
        return this.list(Wrappers.<Role>lambdaQuery().eq(Role::getRoleCode, roleCode).eq(Role::getDelFlag, CommonConstant.DEL_NO)).stream().findFirst().orElse(null);
    }

    public Role findRoleById(String id) {
        return this.getById(id);
    }

    public Result findRoles(Role role) {

        return Result.data(this.page(new Page<>(role.getPageNum(), role.getPageSize()), Wrappers.<Role>lambdaQuery()
                .eq(StringUtils.isNotBlank(role.getRoleCode()), Role::getRoleCode, role.getRoleCode())
                .eq(StringUtils.isNotBlank(role.getRoleName()), Role::getRoleName, role.getRoleName())));
    }

    public Boolean existRoleCodeFlag(String roleCode) {

        return Objects.nonNull(this.findRoleByCode(roleCode));
    }

    @Transactional(rollbackFor = Exception.class)
    public Result insertRole(Role role) {
        role.setId(null);
        if (this.existRoleCodeFlag(role.getRoleCode())) {
            return Result.error("Code已存在");
        }
        handleObjLog(role);
        this.save(role);
        return Result.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    public Result updateRole(Role role) {
        if (StringUtils.isBlank(role.getId())) {
            return Result.error("角色id必传！");
        }
        handleObjLog(role);
        this.updateById(role);
        return Result.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    public Result deleteRole(String id) {
        Role role = this.findRoleById(id);
        if (Objects.isNull(role)) {
            return Result.error("找不到数据！");
        }
        this.removeById(id);
        return Result.ok();
    }




}
